//
//  WmcHomeVC+Photo.swift
//  YPWatermarkCamera
//
//  Created by 赵洋 on 2022/10/14.
//

import UIKit

extension WmcHomeVC {
    /// 拍照模式
    func photoMode() {
        // 顶部
        headerView.switchMode(.photo, cameraView: cameraView)
        // 中部
        switchMode(.photo)
        // 底部
        footerView.switchMode(.photo)
        positioningBtn.isHidden = false
    }

    /// 点击拍照
    func clickTakePhoto() {
        let cameraStatus = WmcAuthorizedManager.camera()
        let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
        if cameraStatus.info.isAvailable {
            if photoAlbumStatus.info.isAvailable || viewModel.hasAlbumAuthorizationAlertForTakePhotoShown  {
                // 询问代理
                if let watermarkModel = watermarkContentView.watermarkModel,
                   let delegateAction = homeDelegate?.photoWillTakeAction(.current,
                                                                          watermarkModel: watermarkModel)
                {
                    delegateAction.transactionDefaultCase { [weak self] in
                        guard let weakSelf = self else { return }
                        weakSelf.takePhotoAction()
                    }
                } else { // 默认实现
                    takePhotoAction()
                }
            } else {
                WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
                viewModel.hasAlbumAuthorizationAlertForTakePhotoShown = true
            }
        } else {
            WmcAuthorizedManager.showCameraPermissionAlert()
        }
    }

    /// 拍照
    func takePhotoAction() {
        // 禁止息屏
        UIApplication.shared.isIdleTimerDisabled = true
        // 锁定操作
        lockAction()
        // 停止虚线闪烁
        controlView.stopFlashDottedLayer()
        // 获取是哪里来的延时
        var _currentDelayTime = 0
        switch viewModel.functionMode {
        case .photo, .photoAndCombine:
            _currentDelayTime = viewModel.delayTime.info.time
        default: break
        }
        // 进行拍照动画
        controlView.setDelayTakePhotoAnimation(_currentDelayTime)
        // 进行延迟拍摄
        startDelayTakePhoto(_currentDelayTime)
        // 设置拍照次数（新手引导需要）
        if footerView.isTakePhotoModel() {
            setTakePhotoCount()
        }
    }

    /// 开始拍照
    func startDelayTakePhoto(_ time: Int) {
        perform(#selector(self.takePhoto), with: nil, afterDelay: TimeInterval(time))
    }

    /// 拍照方法
    @objc
    func takePhoto() {
        // 拍照闪一下动画
        takePhotoAnimation()
        // 延时/直拍结束
        cameraView?.collectPhoto { [weak self] image in
            guard let weakSelf = self else { return }
            switch weakSelf.viewModel.functionMode {
            // 数钢筋
            case .rebarCount:
                var uploadImage = image
                if let rotateImage = uploadImage.yp.setRotate(angle: 360),
                   rotateImage.size.width > 0,
                   rotateImage.size.height > 0 {

                    UIGraphicsBeginImageContextWithOptions(rotateImage.size, false, 1)
                    let drawRect = CGRect(origin: .zero, size: rotateImage.size)
                    rotateImage.draw(in: drawRect)
                    let drawImage = UIGraphicsGetImageFromCurrentImageContext()
                    UIGraphicsEndImageContext()

                    if let drawImage = drawImage {
                        uploadImage = drawImage
                    }
                }
                
                let vm = WmcRecognitionResultVM()
                vm.model = weakSelf.viewModel.recognitionModel
                vm.image = uploadImage
                WmcNavigatorManager.push(.recognitionResult, parms: vm)
                
                // 开放拍照按钮
                weakSelf.unlockAction()
                
            // 常规拍照
            case .photo:
                // 当前分辨率
                let resolution = weakSelf.viewModel.resolution
                // 修改图片大小
                let resizeImage = weakSelf.resize(image: image, targetSize: CGSize(width: resolution.width, height: resolution.height))
                // 二维码验证控件
                var qrcodeView: WmcQRCodeVerifyView?
                if weakSelf.viewModel.showQrcodeVerify {
                    qrcodeView = weakSelf.dynamicQRView
                }
                // 进行处理图片
                weakSelf.viewModel.fotoMix(resizeImage, watermarkContentView: weakSelf.watermarkContentView, qrcodeView: qrcodeView) {
                    // 允许息屏
                    YPGCD.Main {
                        UIApplication.shared.isIdleTimerDisabled = false
                    }
                    // 开放拍照按钮
                    weakSelf.unlockAction()
                }
            // 边拍边拼
            case .photoAndCombine:
                // 合成图片
                weakSelf.viewModel.fotoMix(image, watermarkContentView: weakSelf.watermarkContentView)
            default:
                // 开放拍照按钮
                weakSelf.unlockAction()
            }
        }
    }

    /// 取消拍照
    func cancelDelayTakePhoto() {
        unlockAction()
        controlView.cancelDelayTakePhotoAnimation()
        WmcHomeVC.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.takePhoto), object: nil)
    }

    /// 解锁锁定操作
    func lockAction() {
        YPGCD.Main { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.lockActionView.isHidden = false
        }
    }

    /// 解锁锁定操作
    func unlockAction() {
        YPGCD.Main { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.lockActionView.isHidden = true
        }
    }

    /// 拍照动画
    func takePhotoAnimation() {
        footerView.actionBtn.transform = CGAffineTransform.YP.CreateScale(1)
        Wmc_SpringAnimation(withDuration: 0.2) { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.footerView.actionBtn.transform = CGAffineTransform.YP.CreateScale(0.8)
        } completion: {
            Wmc_SpringAnimation(withDuration: 0.2) { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.footerView.actionBtn.transform = CGAffineTransform.YP.CreateScale(1)
            }
        }
        controlView.backgroundColor = .clear
        Wmc_SpringAnimation(withDuration: 0.1) { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.controlView.backgroundColor = .white.yp.alpha(0.9)
        } completion: {
            Wmc_SpringAnimation(withDuration: 0.1) { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.controlView.backgroundColor = .clear
            }
        }
    }

    /// 拍照后去预览页
    func takePhotoToPreview(_ result: YPWmcManager.PhotoResult) {
        let watermarkPhoto = result.watermarkPhoto
        let standardPhoto = result.standardPhoto
        let watermarkModel = result.watermarkModel
        let qrcodePhoto = result.qrcodePhoto
        var isTakePhotoToPreview = true // 默认去
        // 获取业务方设置的是否去预览页
        if let isToPreview = homeDelegate?.photoDisposeToPreview(.current,
                                                                 watermarkModel: watermarkModel)
        {
            isTakePhotoToPreview = isToPreview
        }
        let isUseTakePhotoToPreviewCell = WmcCameraSettingVM.checkUseCell(type: .takePhotoToPreview)
        if isUseTakePhotoToPreviewCell { // 使用了拍照后确认cell
            // 检查设置的是否去预览页
            let userTakePhotoToPreview = WmcPreferenceSettingsManager.shared.cameraSetting.takePhotoToPreview
            isTakePhotoToPreview = userTakePhotoToPreview
        }
        
        // 要去确认预览页
        if isTakePhotoToPreview {
            if let isToPreviewAction = homeDelegate?.photoWillToPreviewAction(.current,
                                                                              photoResult: result)
            {
                isToPreviewAction.transactionDefaultCase { [weak self] in
                    guard let weakSelf = self else { return }
                    weakSelf.toPreviewAction(result)
                }
            } else {
                toPreviewAction(result)
            }
        } else {
            // 去登录弹窗(已处理宿主包情况)
            viewModel.newUserTakePhotoAlert()
            // 直接保存，使用拍摄时的水印模型
            viewModel.saveImage(watermarkPhoto: watermarkPhoto,
                                standardPhoto: standardPhoto,
                                watermarkModel: watermarkModel,
                                qrcodePhoto: qrcodePhoto)
            // 回调代理通知
            homeDelegate?.photoDisposeComplete(.current,
                                               photoResult: result)
            
        }
    }

    /// 拍照后去预览页的事务钩子
    func toPreviewAction(_ result: YPWmcManager.PhotoResult) {
        let watermarkPhoto = result.watermarkPhoto
        let standardPhoto = result.standardPhoto
        let watermarkModel = result.watermarkModel
        let qrcodePhoto = result.qrcodePhoto
        // 进入预览页
        let vm = WmcPhotoPreviewVM()
        vm.aspectRatio = viewModel.photoAspectRatio
        vm.watermarkPhoto = watermarkPhoto
        vm.standardPhoto = standardPhoto
        vm.watermarkModel = watermarkModel
        vm.qrImage = qrcodePhoto
        vm.watermarkCenterPoint = watermarkContentView.watermarkView?.center
        vm.saveAlbumBlock = { [weak self] watermarkPhoto, standardPhoto, wmModel, qrcodePhoto in
            guard let weakSelf = self else { return }
            // 确认页可能会存在切换水印的问题
            weakSelf.viewModel.saveImage(watermarkPhoto: watermarkPhoto,
                                         standardPhoto: standardPhoto,
                                         watermarkModel: wmModel,
                                         qrcodePhoto: qrcodePhoto)
        }
        vm.saveBackBlock = { [weak self] in
            guard let weakSelf = self else { return }
            // 去登录弹窗(已处理宿主包情况)
            weakSelf.viewModel.newUserTakePhotoAlert()
        }
        vm.retakeBackBlock = { [weak self] in
            guard let weakSelf = self else { return }
            // 去登录弹窗(已处理宿主包情况)
            weakSelf.viewModel.newUserTakePhotoAlert()
        }

        WmcNavigatorManager.push(.photoPreview, parms: vm)
    }
    
    /// 调整图片的大小,生成新的图片
    private func resize(image: UIImage, targetSize: CGSize) -> UIImage {
        guard targetSize.width > 0 && targetSize.height > 0 else { return image }
        UIGraphicsBeginImageContextWithOptions(targetSize, false, image.scale)
        image.draw(in: CGRect(origin: .zero, size: targetSize))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage ?? image
    }
    
    
}
